var APP_VERSION = '1.0.32';
var userInfo = null;
/***************** Base Object Extension *******************/
// 是否在微信内
function inWechat() {
    return navigator.userAgent.match(/MicroMessenger\/(\d+)\./i);
}

// 判断 是否是PC
//function isPC() {
//	let p = navigator.platform;
//	return p.indexOf("Win") === 0 || p.indexOf("Mac") === 0;
//}

// 是否在APP内
function inApp() {
    return localCache('__IN_APP__');
}

function add0(m){return m<10?'0'+m:m }
function date_format(t)
{
    if(!t) {
        return '0000-00-00';
    }
    //t是整数，否则要parseInt转换
    var time = new Date(t);
    var y = time.getFullYear();
    var m = time.getMonth()+1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return y+'-'+add0(m)+'-'+add0(d);
}
function datetime_format(t)
{
    //t是整数，否则要parseInt转换
    var time = new Date(t);
    var y = time.getFullYear();
    var m = time.getMonth()+1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return y+'-'+add0(m)+'-'+add0(d)+' '+add0(h)+':'+add0(mm)+':'+add0(s);
}
function http_build_query (formdata, url) { // eslint-disable-line camelcase
    //  discuss at: http://locutus.io/php/http_build_query/
    // original by: Kevin van Zonneveld (http://kvz.io)
    // improved by: Legaev Andrey
    // improved by: Michael White (http://getsprink.com)
    // improved by: Kevin van Zonneveld (http://kvz.io)
    // improved by: Brett Zamir (http://brett-zamir.me)
    //  revised by: stag019
    //    input by: Dreamer
    // bugfixed by: Brett Zamir (http://brett-zamir.me)
    // bugfixed by: MIO_KODUKI (http://mio-koduki.blogspot.com/)
    //      note 1: If the value is null, key and value are skipped in the
    //      note 1: http_build_query of PHP while in locutus they are not.
    //   example 1: http_build_query({foo: 'bar', php: 'hypertext processor', baz: 'boom', cow: 'milk'}, '', '&amp;')
    //   returns 1: 'foo=bar&amp;php=hypertext+processor&amp;baz=boom&amp;cow=milk'
    //   example 2: http_build_query({'php': 'hypertext processor', 0: 'foo', 1: 'bar', 2: 'baz', 3: 'boom', 'cow': 'milk'}, 'myvar_')
    //   returns 2: 'myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&php=hypertext+processor&cow=milk'

    var value, key, tmp = [], argSeparator = '&';

    var _httpBuildQueryHelper = function (key, val, argSeparator) {
        var k, tmp = [];
        if (val === true) {
            val = '1';
        } else if (val === false) {
            val = '0';
        }
        if (val !== null) {
            if (typeof val === 'object') {
                for (k in val) {
                    if (val[k] !== null) {
                        tmp.push(_httpBuildQueryHelper(key + '[' + k + ']', val[k], argSeparator));
                    }
                }
                return tmp.join(argSeparator);
            } else if (typeof val !== 'function') {
                return encodeURIComponent(key) + '=' + encodeURIComponent(val);
            } else {
                throw new Error('There was an error processing for http_build_query().');
            }
        } else {
            return '';
        }
    };

    if (!argSeparator) {
        argSeparator = '&';
    }
    for (key in formdata) {
        value = formdata[key];
        var query = _httpBuildQueryHelper(key, value, argSeparator);
        if (query !== '') {
            tmp.push(query);
        }
        url = url.replace(new RegExp(key + '=[^&#]*&?', 'ig'), '');
    }

    url && (url = url.replace(/[&?]+$/, ''));
    var paramString = tmp.join(argSeparator);
    var result = !url ? '' : url + (!paramString ? '' : (url.indexOf('?') != -1 ? '&' : '?'));
    result += paramString;
    return result;
}
console.trace = function() {
	var stack = [],
		caller = arguments.callee.caller;

	while (caller) {
		caller = caller && caller.caller;
		console.log('functions on stack:' + '\n' + caller);
	}

}
function headerBarReset() {
    if(window.statusBarResetDisabled) return;
    if(isHomePage() || isSpecialSalePage()) {
        var StatusbarHeight = plus.navigator.getStatusbarHeight() || 20;
        localCache('STATUS_BAR_HEIGHT', StatusbarHeight, 30);
        $('.sctouch-home-top').css({
            'padding-top': StatusbarHeight
        });
        plus.navigator.setStatusBarStyle('light');
    } else if (isRedHeadPage() || isSharePage()) {
        plus.navigator.setStatusBarStyle('light');
    } else {
        plus.navigator.setStatusBarStyle('dark');
    }
}

// 四舍五入
Number.prototype.round = function (n) {
    var digit = Math.pow(10, n);
    return Math.round(this*digit)/digit;
};
// 进位取整
Number.prototype.ceil = function (n) {
    var digit = Math.pow(10, n);
    return Math.ceil(this*digit)/digit;
};
// 退位取整
Number.prototype.floor = function (n) {
    var digit = Math.pow(10, n);
    return Math.floor(this*digit)/digit;
}
// 去除前后空格
String.prototype.trim = function() {
    return this.replace( /(^\s*)|(\s*$)/g, '');
}
// 字符串转化为整型
String.prototype.toInt = function() {
    var num = parseInt(this);
    return isNaN(num) ? 0 : num;
}
// 字符串转化为浮点型
String.prototype.toFloat = function() {
    var num = parseFloat(this);
    return isNaN(num) ? 0 : num;
}
// 字符串截取替换
String.prototype.strCut = function(len, replaceWith) {
    var string = this;
    return string.length > len ? string.substr(0, len - 3) + (replaceWith || '...') : string;
}
// 首字母大写
String.prototype.ucFirst = function() {
    var string = this;
    return string[0].toUpperCase() + string.substr(1);
}
// 替换全部（ 仿 php preg_replace ）
String.prototype.replaceAll = function(from, to) {
    var string = this;
    for(var i in from) {
        var regexp = new RegExp(from[i], 'g');
        string = string.replace(regexp, to[i]);
    }
    return string;
}

// 删除其中一项（,隔开）
String.prototype.remove = function (value) {
    var separator = arguments[1] || ',';
    var dataArray = this.split(separator);

    var index = dataArray.indexOf(value);
    if(index >= 0) {
        dataArray.splice(index, 1);
    }

    return dataArray.join(separator);
}

// 字符格式化
String.prototype.number_format = Number.prototype.number_format = function (decimals, decPoint, thousandsSep) {
    var number = this;
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '')
    var n = !isFinite(+number) ? 0 : +number
    var prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
    var sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep
    var dec = (typeof decPoint === 'undefined') ? '.' : decPoint
    var s = ''

    var toFixedFix = function (n, prec) {
        var k = Math.pow(10, prec)
        return '' + (Math.round(n * k) / k)
            .toFixed(prec)
    }

    // @todo: for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep)
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || ''
        s[1] += new Array(prec - s[1].length + 1).join('0')
    }

    return s.join(dec);
};
// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

// 下载wgt方法
function downloadWgt (wgtUrl, label){
    return new Promise(function (resolve, reject) {
        plus.nativeUI.showWaiting("开始下载更新 "+label+" ...");
        plus.downloader.createDownload( wgtUrl, {}, function(d,status){
            plus.nativeUI.closeWaiting();
            if ( status === 200 ) {
                mui.toast("下载更新包成功 "+label + ' ...');
                installWgt(d.filename, label).then(function () {
                    resolve('success');
                }).catch(function (result) {
                    reject(result);
                }); // 安装wgt方法
            } else {
                reject("下载更新包失败 " +label + ' ...');
            }
        }).start();
    });
}

// 安装wgt方法
function installWgt(path, label) {
    return new Promise(function (resolve, reject) {
        plus.nativeUI.showWaiting("安装更新文件 "+label + ' ...');
        plus.runtime.install(path, {}, function () {
            plus.nativeUI.closeWaiting();
            mui.toast("安装更新文件成功 " +label + ' ...');
            resolve('success');
        }, function (e) {
            plus.nativeUI.closeWaiting();
            reject("安装更新包失败[" + e.code + "]：" + e.message);
        });
    });
}

function isPlusReady() {
    return typeof plus !== 'undefined';
}




var baseApi = {};
mui.each(['get', 'post'], function(index, method) {
    baseApi[method] = function(api, data, callback, errorCallBack, completeCallback) {
        api = '/' + api.replace(/^\/|\/$/g, '');
        if(typeof data === 'function') {
            callback = data;
            data = {};
        }
        if(!callback) {
            callback = function(result) {
                mui.toast(result.result);
            }
        }
        if(!errorCallBack) {
            errorCallBack = function () {}
        }
        if(!completeCallback) {
            completeCallback = function () {}
        }

        // 如果是网络请求，走 原生
        // if(api === 'service/httpget' && typeof plus !== 'undefined') {
        //     mui.get(data.url, function (result) {
        //         // 修正接口错误
        //         result = result.replace(/:NaN/img, ':null');
        //         console.log(result);
        //         callback(JSON.parse(result));
        //         completeCallback();
        //     }, 'string');
        //     return;
        // }

        var url = http_build_query({
            key: getCookie('key'),
            _random: Math.random(),
            v: APP_VERSION
        }, ApiUrl + api);

        var params = {
            url: url,
            type: method.toUpperCase(),
            data: data,
            dataType: 'json',
            beforeSend: function () {
            },
            error: function (res) {
            },
            success: function(result) {
                // 版本检测
//              APPCheckUpdate(result);
                if(result.code == 0 || result.code == 20000) {
                    if(typeof result.login !== 'undefined' && result.login == 0) {
                        delCookie('key');
                        if(!checkLoginStatus()) return;
                    } else {
                        mui.toast(result.message);
                    }
                    errorCallBack(result);
                } else if(result.code == 302) {
                    location.href = result.url;
                } else if(result.code == 10000) {
                    return callback(result.result, result);
                } else {
                    mui.toast(result.message);
                }
            },
            complete: function (result) {
                window.form_submitted = false;
                return completeCallback(result);
            }
        }
        return $.ajax(params);
    };
});

/**
 * 非空判断
 * 判断传入值是否为 null，undefined，“”,返回true/false
 * */
function isEmpty(value) {
    var flg = false;
    if(value == undefined || value == "" || value == null || value == "none" || value == NaN) {
        flg = true;
    }

    return flg;
}
// 获取请求参数
// name：参数名称
function getQueryString(name) {
    // 只从 url 里获取参数
    if(false && typeof plus !== 'undefined') {
        let self = plus.webview.currentWebview();
        let params = self.params;
        if(name) {
            var value = params[name];
            if(isEmpty(value)) {
                value = ""
            }
            return decodeURIComponent(value);
        } else {
            return params;
        }
    } else {
        if(name) {
            var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r!=null) return decodeURIComponent(r[2]); return '';
        } else {
            let params = window.location.search.substr(1).split('&');
            var query = {};
            for(var i = 0; i < params.length; i++) {
                if(params[i]) {
                    var arr = params[i].split('=');
                    query[arr[0]] = decodeURIComponent(arr[1]);
                }
            }
            return query;
        }
    }
}
function addCookie(e, t, a) {
    return localCache(e, t, a);
}

// 本地缓存查询及设置
function localCache(key, data, t) {
    t = (t || 1) * (86400 * 1000);	// 默认缓存1天

    key = 'DATA_CACHE_' + key;
    if(t < 0) {
        localStorage.removeItem(key);
    }
    // 取值
    else if(typeof data === 'undefined') {
        var cache = localStorage.getItem(key);
        if(cache && cache !== 'undefined') {
            cache = JSON.parse(cache);
            if(cache.expire > (new Date).getTime()) {
                return cache.data;
            }
        }
        return '';
    }
    else {
        var cache = {
            expire: (new Date).getTime() + t,
            data: data
        };

        cache = JSON.stringify(cache);
        localStorage.setItem(key, cache);
    }

}

// 设置本地存储用户信息
function setLocalUserInfo(info) {
	userInfo = info;
	localStorage.setItem('user_info', JSON.stringify(info || {}));
}
// 获取本地存储用户信息
function getLocalUserInfo() {
	// 免登陆页面
	if(!needUserInfo()) {
		return;
	}
	if(userInfo) {
        console.log('userInfo: ', user);
		return userInfo;
	}
	var user = localStorage.getItem('user_info');

    console.log('UserRawData: ', user);
	if(!user || user == 'undefined') return null;
	user = JSON.parse(user);
	console.log('userInfo: ', user);
	if(!user || !user.Pid) {
		return null;
	} else {
		return user;
	}
}
// 初始化用户信息
if(localStorage.getItem('user_info')) {
	userInfo = getLocalUserInfo();
}
// 是否需要用户信息
function needUserInfo() {
	return /(traffic\/taxi|service\/rescue|user\/|)/.test(location.href);
}
// 检查登陆状态
function checkUserLogin() {
	console.log(!userInfo && /(login_mobile|register_mobile)\.html/.test(location.href) === false);
	if(!userInfo && /(login_mobile|register_mobile)\.html/.test(location.href) === false) {
		 pageChange("../member/login_mobile.html");
	}
}
// 退出登录
function userLogout() {
	userInfo = null;
	localStorage.setItem('user_info', null);	
	//checkUserLogin();
}




function setCookie(name, value, days) {
    return localCache(name, value, days);
}
function getCookie(name) {
    if(inApp() && name === 'inviter_id') {
        // APP里面不显示邀请码
        return '';
    }
    return localCache(name);
}
function delCookie(name) {
    return localCache(name, null, -1);
}

// 关闭登录 webview
function closeWebview(pageID, duration, delay) {
    console.log(pageID);
    console.log(pageID.id);
    setTimeout(function () {
        plus.webview.close( pageID, null, duration || 0);
    }, delay || 0)
}

// 关闭登录页webview
function closeLoginWebview() {
    var list = ['member/login_mobile', 'member/register_mobile', 'mall/article_show', ];
    list.forEach(function (item) {
        var wb = plus.webview.getWebviewById(item);
        if(wb) {
            closeWebview(wb, 0, 0);
        }
    });
}
// 登录检测
function checkLoginStatus(autoJumpToLogin) {
    var key = getCookie('key');
    if (!key) {
        // 直接跳转去登录
	    pageChange("../member/login_mobile.html");

	    if(!autoJumpToLogin) return;

        // 弹窗提示
        mui.confirm('请登录之后操作', '温馨提示', ['确定', '取消'], function (e) {
            if(e.index == 0) {
                pageChange("../member/login_mobile.html")
            }
        }, 'div');
        return false;
    } else {
        return true;
    }
}
function checkLogin(e) {
    if (e == 0) {
        //检测KEY值不正确则删除KEY值重新登录。
        delCookie('key');
        if(!checkLoginStatus()) return;
        return false
    } else {
        return true
    }
}

// 获取用户类型
function getUserType() {
    return 1;   // 暂时
    return localCache('_user_type_');
}

// 是否店主
function isInviterUser() {
    return localCache('_user_type_')
}

// 获取用户类型
function setUserType(userType) {
    return localCache('_user_type_', userType, 365);
}

// 获取登录用户信息
function getUserInfo(refresh = false) {
    return new Promise(function (resolve, reject) {
        let localUserInfo = localCache('__local_user_info__');
        if(!refresh && localUserInfo) {
            resolve(localUserInfo);
            return;
        }
	    // 获取当前登录用户
	    baseApi.get('Member/index.html', {}, function (result) {
            checkLogin(result.login);
		    result.member_info.store_info = result.store_info;
            localCache('__local_user_info__', result.member_info, 1);
            resolve(result.member_info);
	    });
    });
}

function contains(e, t) {
    var a = e.length;
    while (a--) {
        if (e[a] === t) {
            return true
        }
    }
    return false
}
function buildUrl(e, t) {
    switch (e) {
        case "keyword":
            return "../mall/product_list.html?keyword=" + encodeURIComponent(t);
        case "goods":
            return "../mall/product_detail.html?goods_id=" + t;
        case "url":
            return t
    }
    return WapSiteUrl
}
function writeClear(e) {
    if (e.val().length > 0) {
        e.parent().addClass("write")
    } else {
        e.parent().removeClass("write")
    }
    btnCheck(e.parents("form"))
}
function btnCheck(e) {
    var t = true;
    e.find("input").each(function() {
        if ($(this).hasClass("no-follow")) {
            return
        }
        if ($(this).val().length == 0) {
            t = false
        }
    });

    t = true;
    if (t) {
        e.find(".btn").parent().addClass("ok")
    } else {
        e.find(".btn").parent().removeClass("ok")
    }
}
function getSearchName() {
    var e = getQueryString("keyword");
    if (e == "") {
        if (getCookie("deft_key_value") == null) {
            $.getJSON(ApiUrl + "/Index/search_hot_info.html",
                function(e) {
                    var t = e.result.hot_info;
                    if (typeof t.name != "undefined") {
                        $("#keyword").attr("placeholder", t.name);
                        $("#keyword").html(t.name);
                        addCookie("deft_key_name", t.name, 1);
                        addCookie("deft_key_value", t.value, 1)
                    } else {
                        addCookie("deft_key_name", "", 1);
                        addCookie("deft_key_value", "", 1)
                    }
                })
        } else {
            $("#keyword").attr("placeholder", getCookie("deft_key_name"));
            $("#keyword").html(getCookie("deft_key_name"))
        }
    }
}

function getCartCount(e, t) {
    var a = 0;
    if (getCookie("key") !== null && !getCookie("cart_count")) {
        var e = getCookie("key");
        $.ajax({
            type: "post",
            url: ApiUrl + "/Membercart/cart_count.html",
            data: {
                key: e
            },
            dataType: "json",
            async: false,
            success: function(e) {
                if (typeof e.result.cart_count != "undefined") {
                    delCookie("cart_count")
                    addCookie("cart_count", e.result.cart_count, t);
                    a = e.result.cart_count;
                }
            }
        })
    } else {
        a = getCookie("cart_count")
    }
    if (a > 0 && $(".sctouch-nav-menu").has(".cart").length > 0) {
        $(".sctouch-nav-menu").has(".cart").find(".cart").parents("li").find("sup").show();
        $("#header-nav").find("sup").show();
    }

    setTimeout(function () {
        if($('#head_nav_cart').length >= 0) {
            $('#foot_nav_cart').html(a > 0 ? '<sup>'+a+'</sup>' : '');
        }
        if($('#foot_nav_cart').length >=0) {
            $('#foot_nav_cart').html(a > 0 ? '<sup>'+a+'</sup>' : '');
        }
    }, 100);
}
$(function() {
    $(".input-del").on('tap',function() {
        $(this).parent().removeClass("write").find("input").val("");
        btnCheck($(this).parents("form"))
    });
    $("body").on("tap", "label",
        function() {
            if ($(this).has('input[type="radio"]').length > 0) {
                $(this).addClass("checked").siblings().removeAttr("class").find('input[type="radio"]').removeAttr("checked")
            } else if ($(this).has('[type="checkbox"]')) {
                if ($(this).find('input[type="checkbox"]').prop("checked")) {
                    $(this).addClass("checked")
                } else {
                    $(this).removeClass("checked")
                }
            }
        });
    if ($("body").hasClass("scroller-body")) {
        new IScroll(".scroller-body", {
            mouseWheel: true,
            click: true
        })
    }
    $("#header").on("tap", "#header-nav",
        function() {
            if ($(".sctouch-nav-layout").hasClass("show")) {
                $(".sctouch-nav-layout").removeClass("show")
            } else {
                $(".sctouch-nav-layout").addClass("show")
            }
        });
    $("#header2").on("tap", "#header-nav2",
        function() {
            if ($(".sctouch-nav-layout").hasClass("show")) {
                $(".sctouch-nav-layout").removeClass("show")
            } else {
                $(".sctouch-nav-layout").addClass("show")
            }
        });
    $("#header").on("tap", ".sctouch-nav-layout",
        function() {
            $(".sctouch-nav-layout").removeClass("show")
        });
    $(document).scroll(function() {
        $(".sctouch-nav-layout").removeClass("show")
    });
    //getSearchName();
    //getCartCount();
    $(document).scroll(function() {
        e()
    });
    $(".fix-block-r,footer").on("tap", ".gotop",
        function() {
            btn = $(this)[0];
            this.timer = setInterval(function() {
                    $(window).scrollTop(Math.floor($(window).scrollTop() * .8));
                    if ($(window).scrollTop() == 0) clearInterval(btn.timer, e)
                },
                10)
        });
    function e() {
        $(window).scrollTop() == 0 ? $("#goTopBtn").addClass("hide") : $("#goTopBtn").removeClass("hide")
    }
});
(function($) {
    $.extend($, {
        scrollTransparent: function(e) {
            var t = {
                valve: "#header",
                scrollHeight: 50
            };
            var e = $.extend({},
                t, e);
            function a() {
                $(window).scroll(function() {
                    if ($(window).scrollTop() <= e.scrollHeight) {
                        $(e.valve).addClass("transparent").removeClass("posf")
                    } else {
                        $(e.valve).addClass("posf").removeClass("transparent")
                    }
                })
            }
            return this.each(function() {
                a()
            })()
        },
        areaSelected: function(options) {
            var defaults = {
                success: function(e) {}
            };
            var options = $.extend({},
                defaults, options);
            var ASID = 0;
            var ASID_1 = 0;
            var ASID_2 = 0;
            var ASID_3 = 0;
            var ASNAME = "";
            var ASINFO = "";
            var ASDEEP = 1;
            var ASINIT = true;
            function _init() {
                if ($("#areaSelected").length > 0) {
                    $("#areaSelected").remove()
                }
                var e = '<div id="areaSelected">' + '<div class="sctouch-full-mask left">' + '<div class="sctouch-full-mask-bg"></div>' + '<div class="sctouch-full-mask-block">' + '<div class="header">' + '<div class="header-wrap">' + '<div class="header-l"><a href="javascript:void(0);"><i class="back iconfont"></i></a></div>' + '<div class="header-title">' + "<h1>选择地区</h1>" + "</div>" + '<div class="header-r"><a href="javascript:void(0);"><i class="close iconfont"></i></a></div>' + "</div>" + "</div>" + '<div class="sctouch-main-layout">' + '<div class="sctouch-single-nav">' + '<ul id="filtrate_ul" class="area">' + '<li class="selected"><a href="javascript:void(0);">一级地区</a></li>' + '<li><a >二级地区</a></li>' + '<li><a >三级地区</a></li>' + "</ul>" + "</div>" + '<div class="sctouch-main-layout-a"><ul class="sctouch-default-list"></ul></div>' + "</div>" + "</div>" + "</div>" + "</div>";
                $("body").append(e);
                _getAreaList();
                _bindEvent();
                _close()
            }
            function _getAreaList() {
                $.ajax({
                    type: "get",
                    url: ApiUrl + "/Area/area_list.html",
                    data: {
                        area_id: ASID
                    },
                    dataType: "json",
                    async: false,
                    success: function(e) {
                        if (e.result.area_list.length == 0) {
                            _finish();
                            return false
                        }
                        if (ASINIT) {
                            ASINIT = false
                        } else {
                            ASDEEP++
                        }
                        $("#areaSelected").find("#filtrate_ul").find("li").eq(ASDEEP - 1).addClass("selected").siblings().removeClass("selected");
                        checkLogin(e.login);
                        var t = e.result;
                        var a = "";
                        for (var n = 0; n < t.area_list.length; n++) {
                            a += '<li><a data-id="' + t.area_list[n].area_id + '" data-name="' + t.area_list[n].area_name + '"><h4>' + t.area_list[n].area_name + '</h4><span class="arrow-r"></span> </a></li>'
                        }
                        $("#areaSelected").find(".sctouch-default-list").html(a).parent().scrollTop(0);

                        // if (typeof myScrollArea == "undefined") {
                        //     if (typeof IScroll == "undefined") {
                        //         $.ajax({
                        //             url: WapSiteUrl + "/js/iscroll.js?v2.0.43",
                        //             dataType: "script",
                        //             async: false
                        //         })
                        //     }
                        //     myScrollArea = new IScroll("#areaSelected .sctouch-main-layout-a", {
                        //         mouseWheel: true,
                        //         click: true
                        //     })
                        // } else {
                        //     myScrollArea.refresh();
                        //     myScrollArea.scrollTo(0,0,0);
                        // }
                    }
                });
                return false
            }
            function _bindEvent() {
                $("#areaSelected").find(".sctouch-default-list").off("click", "li > a");
                $("#areaSelected").find(".sctouch-default-list").on("click", "li > a",
                    function() {
                        ASID = $(this).attr("data-id");
                        eval("ASID_" + ASDEEP + "=$(this).attr('data-id')");
                        ASNAME = $(this).attr("data-name");
                        ASINFO += ASNAME + " ";
                        var _li = $("#areaSelected").find("#filtrate_ul").find("li").eq(ASDEEP);
                        _li.prev().find("a").attr({
                            "data-id": ASID,
                            "data-name": ASNAME
                        }).html(ASNAME);
                        if (ASDEEP == 3) {
                            _finish();
                            return false
                        }
                        _getAreaList()
                    });
                $("#areaSelected").find("#filtrate_ul").off("click", "li > a");
                $("#areaSelected").find("#filtrate_ul").on("click", "li > a",
                    function() {
                        if ($(this).parent().index() >= $("#areaSelected").find("#filtrate_ul").find(".selected").index()) {
                            return false
                        }
                        ASID = $(this).parent().prev().find("a").attr("data-id");
                        ASNAME = $(this).parent().prev().find("a").attr("data-name");
                        ASDEEP = $(this).parent().index();
                        ASINFO = "";
                        for (var e = 0; e < $("#areaSelected").find("#filtrate_ul").find("a").length; e++) {
                            if (e < ASDEEP) {
                                ASINFO += $("#areaSelected").find("#filtrate_ul").find("a").eq(e).attr("data-name") + " "
                            } else {
                                var t = "";
                                switch (e) {
                                    case 0:
                                        t = "一级地区";
                                        break;
                                    case 1:
                                        t = "二级地区";
                                        break;
                                    case 2:
                                        t = "三级地区";
                                        break
                                }
                                $("#areaSelected").find("#filtrate_ul").find("a").eq(e).html(t)
                            }
                        }
                        _getAreaList()
                    })
            }
            function _finish() {
                var e = {
                    area_id: ASID,
                    area_id_1: ASID_1,
                    area_id_2: ASID_2,
                    area_id_3: ASID_3,
                    area_name: ASNAME,
                    area_info: ASINFO
                };
                options.success.call("success", e);
                if (!ASINIT) {
                    $("#areaSelected").find(".sctouch-full-mask").addClass("right").removeClass("left")
                }
                return false
            }
            function _close() {
                $("#areaSelected").find(".header-l").off("click", "a");
                $("#areaSelected").find(".header-l").on("click", "a",
                    function() {
                        $("#areaSelected").find(".sctouch-full-mask").addClass("right").removeClass("left")
                    });
                return false
            }
            return this.each(function() {
                return _init()
            })()
        },
        addressSelected: function(options) {
            var defaults = {
                success: function(e) {}
            };
            var options = $.extend({},
                defaults, options);
            var MAP='';
            var LOCAL='';
            var ADDRESS = "";
            var LNG = "";
            var LAT = '';
            function _init() {
                if ($("#addressSelected").length > 0) {
                    $("#addressSelected").remove()
                }
                var e = '<div id="addressSelected">' + '<div class="sctouch-full-mask left">' + '<div class="sctouch-full-mask-bg"></div>' + '<div class="sctouch-full-mask-block">' + '<div class="header">' + '<div class="header-wrap">' + '<div class="header-l"><a href="javascript:void(0);"><i class="back iconfont"></i></a></div>' + '<div class="header-title">' + "<h1>选择地址</h1>" + "</div>" + '<div class="header-r"><a href="javascript:void(0);"><i class="close iconfont"></i></a></div>' + "</div>" + "</div>"+ '<div class="map_content">' + '<div class="location_name"><input type="text" id="map_keywords" placeholder="小区、写字楼、学校"><span class="icon_search"></span></div>' + '<div id="allmap">' + "</div>" +'<div id="r-result"></div>'+ "</div>" + "</div>" + "</div>" + "</div>";
                $("body").append(e);
                _getMap();
                _bindEvent();
                _close()
            }
            function _getMap() {
                MAP = new BMap.Map("allmap");
                var lng = getCookie("longitude");
                var lat = getCookie("latitude");

                if (!lng && !lat) {
                    var geolocation = new BMap.Geolocation();
                    geolocation.getCurrentPosition(function (r) {
                        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
                            var lng = r.point.lng;
                            var lat = r.point.lat;
                            var point = new BMap.Point(lng, lat);
                            MAP.centerAndZoom(point, 16);
                            MAP.addControl(new BMap.NavigationControl());
                            MAP.enableScrollWheelZoom();
                            var marker = new BMap.Marker(point);  // 创建标注
                            MAP.addOverlay(marker);              // 将标注添加到地图中
                            marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
//                        LNG = lng;
//                        LAT = lat;

                        } else {
                            alert('failed' + this.getStatus());
                        }
                    }, {enableHighAccuracy: true});
                }else{
                    var point = new BMap.Point(lng, lat);
                    MAP.centerAndZoom(point, 16);
                    MAP.addControl(new BMap.NavigationControl());
                    MAP.enableScrollWheelZoom();
                    var marker = new BMap.Marker(point);  // 创建标注
                    MAP.addOverlay(marker);              // 将标注添加到地图中
                    marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
                }
                MAP.addEventListener("click", function(e){
//                    alert(e.point.lng + ", " + e.point.lat);
                    MAP.clearOverlays();  //清除标注  或者可以把market 放入数组
                    var point = new BMap.Point(e.point.lng , e.point.lat);
                    var marker = new BMap.Marker(point);
                    MAP.addOverlay(marker);
                    marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
//
//                    LNG = e.point.lng;
//                    LAT = e.point.lat;
                });
                var options = {
                    onSearchComplete: function(results){
                        // 判断状态是否正确
                        if (LOCAL.getStatus() == BMAP_STATUS_SUCCESS){
                            var s = [];
                            for (var i = 0; i < results.getCurrentNumPois(); i ++){
                                s.push('<p class="address_list_wrap" data-lng="'+results.getPoi(i).point.lng+'" data-lat="'+results.getPoi(i).point.lat+'" data-address="'+results.getPoi(i).address+'"><span class="address_mt">'+results.getPoi(i).title + "</span><br><span class='address_mc'> " + results.getPoi(i).address+'</span></p>');
                            }
                            if(results.getCurrentNumPois()>0){

                                MAP.clearOverlays();  //清除标注  或者可以把market 放入数组
                                var point = new BMap.Point(results.getPoi(0).point.lng , results.getPoi(0).point.lat);
                                var marker = new BMap.Marker(point);
                                MAP.centerAndZoom(point, 16);
                                MAP.addOverlay(marker);
                                marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画

//                                            LNG = results.getPoi(0).point.lng;
//                                            LAT = results.getPoi(0).point.lat;
                                document.getElementById("r-result").innerHTML = s.join("");

                            }

                        }
                    }
                };
                LOCAL = new BMap.LocalSearch(MAP, options);
                return false
            }
            function _bindEvent() {
                $("#addressSelected").find(".location_name").off("keyup", "#map_keywords");
                $("#addressSelected").find(".location_name").on("keyup", "#map_keywords",
                    function() {
                        LOCAL.search($('#map_keywords').val());
                    });
                $("#addressSelected").find("#r-result").off("click", ".address_list_wrap");
                $("#addressSelected").find("#r-result").on("click", ".address_list_wrap",
                    function() {
                        var e = {
                            address: $(this).attr('data-address'),
                            lng: $(this).attr('data-lng'),
                            lat: $(this).attr('data-lat')
                        };
                        options.success.call("success", e);
                        $("#addressSelected").find(".sctouch-full-mask").addClass("right").removeClass("left")
                        return false
                    });
            }
            function _close() {
                $("#addressSelected").find(".header-l").off("click", "a");
                $("#addressSelected").find(".header-l").on("click", "a",
                    function() {
                        $("#addressSelected").find(".sctouch-full-mask").addClass("right").removeClass("left")
                    });
                return false
            }
            return this.each(function() {
                return _init()
            })()
        },
        animationLeft: function(e) {
            var t = {
                valve: ".animation-left",
                wrapper: ".sctouch-full-mask",
                scroll: ""
            };
            var e = $.extend({},
                t, e);
            function a() {
                $(e.valve).click(function() {
                    $(e.wrapper).removeClass("hide").removeClass("right").addClass("left");
                    if (e.scroll != "") {
                        if (typeof myScrollAnimationLeft == "undefined") {
                            if (typeof IScroll == "undefined") {
                                $.ajax({
                                    url: WapSiteUrl + "/js/iscroll.js?v2.0.43",
                                    dataType: "script",
                                    async: false
                                })
                            }
                            myScrollAnimationLeft = new IScroll(e.scroll, {
                                mouseWheel: true,
                                click: true
                            })
                        } else {
                            myScrollAnimationLeft.refresh()
                        }
                    }
                });
                $(e.wrapper).on("click", ".header-l > a",
                    function() {
                        $(e.wrapper).addClass("right").removeClass("left")
                    })
            }
            return this.each(function() {
                a()
            })()
        },
        animationUp: function(e) {
            var t = {
                valve: ".animation-up",
                wrapper: ".sctouch-bottom-mask",
                scroll: ".sctouch-bottom-mask-rolling",
                start: function() {},
                close: function() {}
            };
            var e = $.extend({},
                t, e);
            function a() {
                e.start.call("start");
                $(e.wrapper).removeClass("down").addClass("up");
                if (e.scroll != "") {
                    if (typeof myScrollAnimationUp == "undefined") {
                        if (typeof IScroll == "undefined") {
                            $.ajax({
                                url: WapSiteUrl + "/js/iscroll.js?v2.0.43",
                                dataType: "script",
                                async: false
                            })
                        }
                        myScrollAnimationUp = new IScroll(e.scroll, {
                            mouseWheel: true,
                            click: true
                        })
                    } else {
                        myScrollAnimationUp.refresh()
                    }
                }
            }
            return this.each(function() {
                if (e.valve != "") {
                    $(e.valve).on("tap",
                        function() {
                            a()
                        })
                } else {
                    a()
                }
                $(e.wrapper).on("tap", ".sctouch-bottom-mask-bg,.sctouch-bottom-mask-close",
                    function() {
                        $(e.wrapper).addClass("down").removeClass("up");
                        e.close.call("close")
                    })
            })()
        }
    })
})($);
$.fn.ajaxUploadImage = function(e) {
    var t = {
        url: "",
        data: {},
        start: function() {},
        success: function() {}
    };
    var e = $.extend({},
        t, e);
    var a;
    function n() {
        if (a === null || a === undefined) {
            alert("请选择您要上传的文件！");
            return false
        }
        return true
    }
    return this.each(function() {
        $(this).on("change",
            function() {
                var t = $(this);
                e.start.call("start", t);
                let a = t.prop("files")[0];
                if (!n) return false;
                try {
                    var r = new XMLHttpRequest;
                    console.log(r);
                    r.open("post", e.url, true);
                    r.setRequestHeader("X-Requested-With", "XMLHttpRequest");
                    r.onreadystatechange = function() {
                        if (r.readyState == 4) {
                            returnDate = $.parseJSON(r.responseText);
                            e.success.call("success", t, returnDate)
                        }
                    };
                    var i = new FormData;
                    for (k in e.data) {
                        i.append(k, e.data[k])
                    }
                    i.append(t.attr("name"), a);
                    result = r.send(i)
                } catch(o) {
                    mui.toast(o)
                }
            })
    })
};
function loadSeccode() {
    $("#codeimage").attr("src", ApiUrl + "/Seccode/makecode.html" + "?t=" + Math.random())
}
function favoriteGoods(e) {
    var t = getCookie("key");
    if (!t) {
        checkLogin(0);
        return
    }
    if (e <= 0) {
        layer.open({content: '参数错误',skin: 'msg',time: 2});
        return false
    }
    var a = false;
    $.ajax({
        type: "post",
        url: ApiUrl + "/Memberfavorites/favorites_add.html",
        data: {
            key: t,
            goods_id: e
        },
        dataType: "json",
        async: false,
        success: function(e) {
            if (e.code == 10000) {
                a = true
            } else {
                layer.open({content: e.message,skin: 'msg',time: 2});
            }
        }
    });
    return a
}
function dropFavoriteGoods(e) {
    var t = getCookie("key");
    if (!t) {
        checkLogin(0);
        return
    }
    if (e <= 0) {
        layer.open({content: '参数错误',skin: 'msg',time: 2});
        return false
    }
    var a = false;
    $.ajax({
        type: "post",
        url: ApiUrl + "/Memberfavorites/favorites_del.html",
        data: {
            key: t,
            fav_id: e
        },
        dataType: "json",
        async: false,
        success: function(e) {
            if (e.code == 10000) {
                a = true
            } else {
                layer.open({content: e.message,skin: 'msg',time: 2});
            }
        }
    });
    return a
}

function loadScript(url, callback) {
    var script = document.createElement("script");
    script.type = "text/javascript";
    if(typeof(callback) != "undefined"){
        if (script.readyState) {
            script.onreadystatechange = function () {
                if (script.readyState == "loaded" || script.readyState == "complete") {
                    script.onreadystatechange = null;
                    callback();
                }
            };
        } else {
            script.onload = function () {
                callback();
            };
        }
    }
    script.src = url;
    document.body.appendChild(script);
}
function countDown(end_time) {
    var res={};
    var endTime = new Date(end_time * 1000);
    var nowTime = new Date();
    var leftTime = parseInt((endTime.getTime() - nowTime.getTime()) / 1000);
    if (leftTime>0) {
        res.day = leftTime ? parseInt(leftTime / (24 * 60 * 60)) : '';
        res.hour = leftTime
            ? formateTime(parseInt((leftTime / (60 * 60)) % 24))
            : '';
        res.minute = leftTime
            ? formateTime(parseInt((leftTime / 60) % 60))
            : '';
        res.second = leftTime ? formateTime(parseInt(leftTime % 60)) : '';
    }

    return res;
}
function formateTime(time) {
    if (time >= 10) {
        return time;
    } else {
        return '0'+time;
    }
}

/**
 * 是否是登录页
 */
function isLoginPage(page) {
	page = page || getCurrentWindow().id;
	return /member\/login_mobile/.test(page);
}
/**
 * 是否是引导页
 */
function isGuidePage(page) {
	page = page || getCurrentWindow().id;
	return /public\/guide/.test(page);
}

/**
 * 是否是登录页
 */
function isSharePage(page) {
	page = page || getCurrentWindow().id;
	return /mall\/share/.test(page);
}

/**
 * 是否是首页
 */
function isHomePage(page) {
    page = page || getCurrentWindow().id;
	return /mall\/index/.test(page);
}

/**
 * 是否是专题页
 */
function isSpecialSalePage(page) {
	page = page || getCurrentWindow().id;
	return /mall\/special_goods_list/.test(page);
}

/**
 * 是否红色头部
 */
function isRedHeadPage(page) {
	return /(mall\/cart_list|member\/member|member\/balance)/.test(page);
}

/**
 * 是否是主页
 */
function isIndexPage(page) {
	return /(mall\/index|mall\/product_first_categroy|mall\/cart_list|member\/member|member\/login_mobile)/.test(page);
}

/**
 * 是否是主页
 */
function isNoNeedLoginPage(page) {
    page = page || location.href;
    return /(mall\/index|mall\/product_first_categroy|search|product_list|product_detail|opening_gift_bag_list|opening_gift_bag_detail|public|member\/document|article|member\/login_mobile|member\/register_mobile)/.test(page);
}

// 判断是否为顶部 webview
function isTopWebview(page) {
    if(typeof page !== 'object') {
        page = plus.webview.getWebviewById(page);
    }
    var topwb = getTopWindow();
    return (page.id === topwb.id);
}

// 登录成功
function loginSuccessCallback() {
    var loginPrevPage = localCache('login_prev_page');

    if(isGuidePage(loginPrevPage.page_id) || isLoginPage(loginPrevPage.page_id)) {
        pageChange("../mall/index.html");
    } else if(loginPrevPage) {
        pageChange('../' + loginPrevPage.page_id + '.html', loginPrevPage.params);
    } else {
        pageChange("../member/member.html");
    }

    localCache('login_prev_page', null, -1);

    setTimeout(function () {
        // 关闭登录页
        closeLoginWebview();
    }, 1000);
}

// 下载
function downloadPoser() {

	var downloadTasks = [];
	var url = $('.layui-m-layer .layui-m-layercont img').attr('src');

	url = http_build_query({download: 1}, url) + '&_t.png';

	plus.nativeUI.showWaiting('开始下载');
	plus.downloader.createDownload(url,{}, function (d,status) {
		plus.nativeUI.closeWaiting();
		if(status == 200){
			plus.gallery.save(d.filename, function () {//保存到相册
				plus.io.resolveLocalFileSystemURL(d.filename, function (enpty) {
					mui.toast('保存成功');
					layer.closeAll();
				});
			})
		}else{
			resolve(0);
		}
	}).start();
}

window.setShareGoodsDetail = function() {

};

// 分享
window.shareImage = function () {
	if(!window.share_goods_subscribe) {
		mui.toast('请先认购产品');
		return;
	}
	// 获取当前登录用户
    getUserInfo().then(function (result) {
	    // 弹出图片
	    layer.open({
		    skin: 'transparent',
		    closeBtn: true,
		    content: '<img width="100%" src="'+http_build_query({
				    goods_id: window.share_goods_subscribe.goods_id,
				    member_id: result.member_id
			    }, ApiUrl+'/share/goods')+'">'+
			    '<div class="share-container"><ul class="share-actions">'
			    +'<li onclick="downloadPoser();">'
			    +'<div class="action-icon iconfont">&#xe90a;</div><div class="action-name">保存此图片</div></li>'
			    +'<li onclick="shareHref(1);">'
			    +'<div class="action-icon iconfont">&#xe62d;</div><div class="action-name">微信</div></li>'
			    +'<li onclick="shareHref(2);">'
			    +'<div class="action-icon iconfont">&#xe900;</div><div class="action-name">QQ</div></li>'
			    +'<li onclick="shareHref(3);">'
			    +'<div class="action-icon iconfont">&#xe62c;</div><div class="action-name">微博</div></li></ul></div>'

		    , area: ['10rem', '10rem']
		    // , btn: ['长按保存图片去分享,点击关闭']
		    //, btn: ['下载','关闭']

		    , yes: function (index) {
			    // layer.close(index);
		    },
		    btn2:function(){
			    layer.close(index); //关闭当前窗口
		    }
	    });
	});
};

/**
 * 弹出分享窗口
 */
function popupShareWebview(params) {
	window.popupWV = plus.webview.currentWebview();
	if (window.popupShareWV) { // 避免快速多次点击创建多个窗口
		return;
	}

	// 获取分享用户信息
    if(!checkLoginStatus()) return;

	getUserInfo().then(function (result) {
	    let height = params.goods_id ? 400 : 320;
		let top = plus.display.resolutionHeight - height;
		params.inviter_id = result.member_id;
		let url = http_build_query(params, "../mall/share.html");

		params.href = params.href || location.href;

		params.href = http_build_query({inviter_id: result.inviter_id}, SiteDomain + '/wap' + params.href.replace(/^.*(\/\w+\/\w+\.html)/, '$1'));
		params.pageSourceId = window.popupWV.id;

		window.popupShareWV = plus.webview.create(url, "mall/share.html", {
			width: '100%',
			height: height,
			top: top,
			scrollIndicator: 'none',
			scalable: false,
			popGesture: 'none'
		}, {
			shareInfo: params
		});
		window.popupShareWV.addEventListener("loaded", function() {
			popupShareWV.show('slide-in-bottom', 300);
		}, false);
		window.popupShareWV.addEventListener("close", function() {
			closePopupShareWV();
		}, false);

		// 显示遮罩层
		window.popupWV.setStyle({
			mask: "rgba(0,0,0,0.5)"
		});
		// 点击关闭遮罩层
		window.popupWV.addEventListener("maskClick", closePopupShareWV, false);
	});

}

// 关闭分享弹窗
function closePopupShareWV() {
	window.popupWV.setStyle({
		mask: "none"
	});
	//避免出现特殊情况，确保分享页面在初始化时关闭
	if (!window.popupShareWV) {
		window.popupShareWV = plus.webview.getWebviewById("share.html");
	}
	if (window.popupShareWV) {
		window.popupShareWV.close();
		window.popupShareWV = null;
	}
}

// 页面跳转
// url：页面url
// params：目标页面参数
// backend：是否是后台加载
function pageChange(url, params, backend) {
    // pagechange 之后不允许重置任务栏
    window.statusBarResetDisabled = true;

    params = params || {};
    var pageID = url.replace(/^.*\/((\w+)\/(\w+))\.html.*$/, '$1');
    // 记录登录前的页面
    if(pageID === 'member/login_mobile' && !localCache('login_prev_page')) {
        localCache('login_prev_page', {
            page_id: location.href.replace(/^.*\/([^\/]+\/[^\/]+)\.html.*$/, '$1'),
            params: getQueryString()
        });
    }
    if(isPlusReady() && /^http/.test(url)) {
        return pageChange('../mall/exlink.html', {
            url, url,
            title: params.title || '站外链接',
            full_screen: params.full_screen || ''
        }, false);
    }
    // 正式环境去除 js 跳转
//  if(!inWechat() && !isPC() && !isPlusReady()) {
//  	setTimeout(function () {
//  		pageChange(url, params, backend);
//  	}, 100);
//  	return;
//  }

    var t = this;
    params._random = Math.random();

    if(!url) return;    // 链接为空

	if(isSharePage(url)) {
		return popupShareWebview(params);
	}

    url = http_build_query(params, url);

    if(typeof plus === 'undefined') {
        location.href = url;
    } else {
        // 如果是主页，直接显示
        var aniShow = 'slide-in-right';
        if (!isLoginPage(location.href) && isIndexPage(url)) {
			// aniShow = 'none';
        }

        // 如果是主页，刷新页面
        var wb = plus.webview.getWebviewById(pageID);

        if (wb && isIndexPage(url)) {
            // 检查地址是否正确
            if ((new RegExp(pageID)).test(wb.getURL())) {
            } else {
                wb.loadURL(url);
            }
            aniShow = 'none';
            plus.webview.show( pageID, aniShow, 300, function () {
                wb.evalJS('pageReload('+JSON.stringify(params)+');');
            });
            return;
        } else if(wb) {
            // 打开新页面，关闭旧页面
            closeWebview(wb, 0, 1000);
        }

        let style = {
	        statusbar: {
		        background: "#F2F2F2"
	        }, //WebviewStatusbarStyles类型,窗口状态栏样式.仅在应用设置为沉浸式状态栏样式下有效,设置此属性后将自动保留系统状态栏区域不被Webview窗口占用(即Webview窗口非沉浸式样式显示).
        };

        //判断不是首页改变导航栏的背景和字体颜色
        if(isHomePage(url) || isSpecialSalePage(url)) {
	        style = {};
        } else if(isRedHeadPage()) {
            style = {
	            background: "#f10d3b"
            }
        }

        let nw = mui.openWindow({
            id: pageID,
            url: url,
            show: {
                autoShow: !backend, //页面loaded事件发生后自动显示，默认为true
                aniShow: aniShow, //页面显示动画，默认为”slide-in-right“；
                duration: 300 //页面动画持续时间，Android平台默认100毫秒，iOS平台默认200毫秒；
            },
	        styles: style,
            createNew: true,
            waiting: {
                autoShow: false
            },
            extras: {params: params}
        });

	    nw.addEventListener('close', function(e){
	        window.statusBarResetDisabled = false;
		    // 改变 statusbar 颜色，背景颜色
            headerBarReset();
		    // 上级页面数据重新加载
		    window.pageReload();
	    }, false);
        nw.addEventListener('show', function(e){
            // 页面显示 改变 statusbar 颜色，背景颜色
            nw.evalJS('headerBarReset();');
        }, false);
    }
};

// 判断当前webview 是否在最顶部
function currentIsTopWindow() {
    return isTopWebview(getCurrentWindow());
}

// 当前页面
function getCurrentWindow() {
	return plus.webview.currentWebview();
}

// 父级页面
function getOpennerWindow() {
	return plus.webview.currentWebview().opener();
}

// 当前页面
function getTopWindow() {
    let all = plus.webview.all();
    return all.pop();
}
// 关闭当前页面
function closeCurrentWindow() {
    if(isPlusReady()) {
	    plus.webview.close(plus.webview.currentWebview());
    } else {
        history.back();
    }
}
// 关闭所有页面
function clearAllWindows() {
    var all = plus.webview.all();

    for(let key in all) {
        if(all[key] !== plus.webview.currentWebview()) {
            plus.webview.close(all[key]);
        }
    }
}

// 获取系统
function getClientType() {
    if(isPlusReady()) {
	    if(mui.os.ios) return 'ios';
	    if(mui.os.android) return 'android';
    } else {
        return 'wap';
    }
}

// 记录搜索关键词
function addSearchHistory(keyword) {
    var history = getCookie('__his_search__') || [];
    var list = [];
    list.push(keyword);
    history.forEach(function (item) {
        if(list.indexOf(item) >= 0) return;
        list.push(item);
    });
    setCookie('__his_search__', list, 365);
}

// 获取搜索记录
function getSearchHistory() {
    return getCookie('__his_search__') || [];
}


//复制内容
function copyToClip(text) {
    var copyInput = $('#copy-input');
    if(copyInput.length == 0) {
        copyInput = $('<input id="copy-input" type="text" value="ss" style="position: fixed;left: -20rem;" />').appendTo('body');
    }
    copyInput.val(text);

    let input = document.getElementById('copy-input');
    input.select();
    document.execCommand('copy',false);
    mui.toast("文本已复制");
}

/************************** 页面初始化 事件监听 及 检测 Start ****************************/

(function () {
    // 如果已经登录，查询用户类型
//  let userType = getUserType();
//  if(!userType && getCookie('key')) {
//      getUserInfo().then(function (result) {
//          setUserType(result.store_info && result.store_info.inviter_state == 1 ? 1 : '');
//      })
//  }
//
//  // 邀请人记录
//  if (getQueryString("inviter_id")) {
//      inviter_id = getQueryString("inviter_id");
//      //计入cookie
//      setCookie('inviter_id', inviter_id, 1);
//  }
//
//  // 自动登录
//  if(getQueryString('auto_login')) {
//      key = getQueryString('key');
//      setCookie('key', key, 30);
//  }
//
//  // 判断登录页判断
//  if(!isNoNeedLoginPage()) {
//      if(!getCookie('key')) {
//          pageChange('../member/login_mobile.html');
//      }
//  }

    /************* PAGE listen start **************/

    // mui全局处理
    mui.init({
        beforeback: function() {
            // 页面回调方法
            if(typeof beforeback === 'function') {
                beforeback.call();
            }
        },
        keyEventBind: {
            backbutton: true //开启back按键监听
        }
    });

    // 页面数据重新加载
    window.pageReload = function() {};

    // plus ready
    mui.plusReady(function() {
	    localCache('__IN_APP__', true);
        headerBarReset();
    	// 记录用户设备信息
    	var deviceInfo = plus.push.getClientInfo();

    	// 存储设备信息
        if(APP_DEBUG || (!localCache('DEVICE_ID_SAVED') && getCookie('key'))) {
            baseApi.post(
                'device/log',
                {
                    device_info: deviceInfo
                },function (result) {
                    if(result === 'success') {
                        localCache('DEVICE_ID_SAVED', 1, 1);
                    }
                }
            );
        }

        // 两次点击退出
        (function () {
            var tuichu = "再按一次退出程序";
            var backButtonPress = 0;

            mui.back = function(event) {
                if(isIndexPage()) {
                    // 首页两次退出
                    backButtonPress++;
                    if(backButtonPress > 1) {
                        var main = plus.android.runtimeMainActivity();
                        main.moveTaskToBack(false);
                        // 关闭所有无用窗口
                        clearAllWindows();
                        return false;
                    } else {
                        plus.nativeUI.toast(tuichu);
                    }
                    setTimeout(function() {
                        backButtonPress = 0;
                    }, 1000);
                    return false;
                } else {
                    // 关闭当前 webwiew
                    closeCurrentWindow();
                }
            };
        }());
    });

    // 节点复制
    $('body').on('tap', '.copy-to-clip', function () {
        let target = $(this).data('target');
        copyToClip($(target).text());
    });

	// 页面跳转
	$('body').on('tap', '.open-url', function() {
		var url = $(this).data('url');
		var data = $(this).data();
		var params = JSON.parse(JSON.stringify(data || {}));

		delete params.url;
		delete params.href;

		// 缓存
		params._random = Math.random();

		pageChange(url, params);

		return false;
	});

	// 页面跳转
	$('body').on('tap', '.ex-open-url', function() {
		var url = $(this).data('url');
		var data = $(this).data();
		var params = JSON.parse(JSON.stringify(data || {}));

		delete params.url;
		delete params.href;

		// 缓存
		params._random = Math.random();

		getOpennerWindow().evalJS('pageChange("'+url+'", '+ JSON.stringify(params) +')');
		closeCurrentWindow();
		return false;
	});


    // 获取焦点时
    $(document).on('focus', '.input-num, .input-float', function () {
        var val = $(this).val().toFloat();
        if(val === 0) $(this).val('');
    });

    // 输入格式（整数）
    $(document).on('input', '.input-num', function () {
        var val = $(this).val();
        var max = $(this).data('max');
        var min = $(this).data('min');
        if(val === '') return;
        val = val.toInt();

        if(max != null && val > max) {
            val = max;
        }
        if(min != null && format_val < min) {
            val = min;
        }
        $(this).val(val);
    });
    // 输入格式（小数）
    $('body').on('input', '.input-float', function () {
        var max = $(this).data('max');
        var min = $(this).data('min');
        var digit = $(this).data('digit') || '';

	    var val = $(this).val();

        if(val === '') return;

        var format_val = val.toFloat();
        if(!(/^\d+\.\d+$/.test(val))) {
            var endword = val[val.length - 1];
            val = val.toFloat();
            val += (endword == '.' ? '.' : '');
        } else if(digit !== null) { // 有效数位
            val = val.replace(new RegExp('(\\..{'+digit+'}).*$'), '$1');
        }

        if(max !== '' && format_val > max) {
            val = max;
        }
        if(min !== '' && format_val < min) {
            val = min;
        }

	    $(this).val(val);
    });
}());